package services;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import play.libs.Codec;
import utils.BizConstants;
import utils.HttpUtils;
import utils.PageUtil;
import vos.CaseSearchVo;
import vos.ResponseInfo;
import vos.ResultVo;
import vos.ReturnCode;

import com.alibaba.fastjson.JSONObject;
import com.aton.db.Config;
import com.aton.db.SessionFactory;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;

import models.DrCase;
import models.DrCaseConfig;
import models.DrCaseExample;
import models.DrCaseTemp;
import models.DrCaseTempExample;
import models.DrCourt;
import models.DrMicrophone;
import models.DrVCase;
import models.DrVCaseExample;
import models.DrVCaseTemp;
import models.DrVCaseTempExample;
import models.SystemLog;
import models.SystemOperator;
import models.mapper.DrCaseConfigMapper;
import models.mapper.DrCaseMapper;
import models.mapper.DrCaseTempMapper;
import models.mapper.DrCourtMapper;
import models.mapper.DrMicrophoneMapper;
import models.mapper.DrVCaseMapper;
import models.mapper.DrVCaseTempMapper;
import models.mapper.SystemLogMapper;

/**
 * 案件服务类
 * @author wangshaoming
 *
 */
public class CaseService {
	public static final Logger log=LoggerFactory.getLogger("countLive");
	/**
	 * 保存案件信息
	 * @param cases 案件基本信息
	 * @param configs 案件基本配置
	 * @param micros 麦克风列表
	 * @param systemOperator 
	 * @param ip 
	 * @param sortname 
	 * @param courtname 
	 * @return
	 */
	public static boolean saveCase(DrCaseTemp cases, DrCaseConfig[] configs,
			DrMicrophone[] micros, String ip, SystemOperator systemOperator, DrCourt court, String sortname) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
		try{
			DrCaseConfigMapper configMapper=ss.getMapper(DrCaseConfigMapper.class);
			DrCaseTempMapper caseMapper=ss.getMapper(DrCaseTempMapper.class);
			DrMicrophoneMapper microMapper=ss.getMapper(DrMicrophoneMapper.class);
			caseMapper.insert(cases);
			//保存案件配置
			if(configs!=null&&configs.length>0){
				for(DrCaseConfig config : configs){
					config.setCaseid(cases.getCaseid());
					config.setConfigid(Codec.UUID());
					configMapper.insert(config);
				}
			}
			if(micros!=null&&micros.length>0){
				//更新麦克风对应列表
				for(DrMicrophone phone : micros){
					microMapper.updateByPrimaryKeySelective(phone);
				}
			}
			//插入日志
			SystemLog log=new SystemLog(Codec.UUID(),systemOperator.getOperatorid(),ip,"新增案件","新增案件案件室为："+court.getCourtname()+"案件种类为："+sortname,new Date());
			SystemLogMapper logMapper=ss.getMapper(SystemLogMapper.class);
			logMapper.insert(log);
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 根据案件室查看案件室是否讯在正在执行的案件
	 * @param courtid 案件室id
	 * @return
	 */
	public static List<DrCase> getByCourtInUse(String courtid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			DrCaseExample example=new DrCaseExample();
			DrCaseExample.Criteria c=example.createCriteria();
			c.andCourtidEqualTo(courtid);
			c.andStatusNotEqualTo(new BigDecimal(2));
			return caseMapper.selectByExample(example);
		}finally{
			ss.close();
		}
	}
	/**
	 * 根据id获取案件信息
	 * @param caseid
	 * @return
	 */
	public static DrCase getById(String caseid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.getSqlSession();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			return caseMapper.selectByPrimaryKey(caseid);
		}finally{
			ss.close();
		}
	}
	/**
	 * 更新案件状态
	 * @param newCase
	 * @return
	 */
	public static boolean updateCase(DrCase newCase,DrCase cases,SystemOperator opr,String Ip,String logMoudle) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			caseMapper.updateByPrimaryKeySelective(newCase);
			SystemLog log=new SystemLog(Codec.UUID(),opr.getOperatorid(),Ip,"更新案件状态",logMoudle,new Date());
			SystemLogMapper logMapper=ss.getMapper(SystemLogMapper.class);
			logMapper.insert(log);
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 调用开庭接口
	 * @param caseid
	 * @param court 
	 * @return
	 */
	public static ResultVo StartInterface(String caseid, DrCourt court) {
		// TODO Auto-generated method stub
		String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?><RequestInfo><Command>Start</Command><Identify>"+caseid+"</Identify>"
				+ "<AddPunc>yes</AddPunc><VadHead>"+court.getVadhead()+"</VadHead><VadSeg>"
						+court.getVadseg()+ "</VadSeg><MaxSecond>"+court.getMaxsecond()+"</MaxSecond></RequestInfo>";
		String Interface_Url=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("LIVE_URL"));
		if(StringUtils.isEmpty(Interface_Url)){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"系统参数asr地址未配置");
			return vo;
		}
		String resMsg=HttpUtils.doPost(Interface_Url, xml);
		log.info("启动开庭接口返回结果："+resMsg);
		if(StringUtils.isEmpty(resMsg)){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"初始化开庭接口失败");
			return vo;
		}
		try{
			XStream xstream=new XStream(new DomDriver());
			xstream.processAnnotations(ResponseInfo.class);
			ResponseInfo info=(ResponseInfo) xstream.fromXML(resMsg);
			if("Success".equals(info.getResCode())){
				ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"调用开庭接口成功",info.getVideoPath());
				return vo;
			}
			else{
				String errMsg=BizConstants.COURTLIVEINTERFACE.get(info.getErrorNo());
				ResultVo vo=new ResultVo(ReturnCode.ErrorCode,errMsg);
				return vo;
			}
		}catch(Exception e){
			e.printStackTrace();
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"调用开庭接口失败");
			return vo;
		}
	}
	/**
	 * 暂停和结束接口
	 * @param type 
	 * @return
	 */
	public static ResultVo getInterFace(String command,String caseid, String type) {
		// TODO Auto-generated method stub
		String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?>"
				+ "<RequestInfo><Command>"+command+"</Command><Identify>"+caseid+"</Identify></RequestInfo>";
		//解析返回结果
		String Interface_Url=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("LIVE_URL"));
		if(StringUtils.isEmpty(Interface_Url)){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"系统参数asr地址未配置");
			return vo;
		}
		String resMsg=HttpUtils.doPost(Interface_Url, xml);
		log.info(type+"接口返回结果："+resMsg);
		if(StringUtils.isEmpty(resMsg)){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"调用接口失败");
			return vo;
		}
		try{
			XStream xstream=new XStream(new DomDriver());
			xstream.processAnnotations(ResponseInfo.class);
			ResponseInfo info=(ResponseInfo) xstream.fromXML(resMsg);
			if("Success".equals(info.getResCode())){
				ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"调用"+type+"接口成功");
				return vo;
			}
			else{
				String errMsg=BizConstants.COURTLIVEINTERFACE.get(info.getErrorNo());
				if("1".equals(info.getErrorNo())){
					ResultVo vo=new ResultVo(ReturnCode.REUPLOAD,errMsg);
					return vo;
				}
				ResultVo vo=new ResultVo(ReturnCode.ErrorCode,errMsg);
				return vo;
			}
		}catch(Exception e){
			e.printStackTrace();
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"调用"+type+"接口失败");
			return vo;
		}
	}
	/**
	 * 初始化接口
	 * @param caseid 案件编号
	 * @param courtid 案件室编号
	 * @return
	 */
	public static ResultVo initInterfase(String caseid, String courtid) {
		// TODO Auto-generated method stub
		//根据案件室获取麦克风
		List<DrMicrophone> phones=DrMicroService.getMicroByCourt(courtid);
		if(phones==null){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"麦克风不存在");
			return vo;
		}
		//组装xml
		String xml="<?xml version=\"1.0\" encoding=\"utf-8\"?><RequestInfo><Command>Init</Command><Url>";
		String micIndex="<MicIndex>";
		for(int i=0;i<phones.size();i++){
			if(i==phones.size()-1){
				xml+=phones.get(i).getMicrocode();
				micIndex+=phones.get(i).getMicroid();
				continue;
			}
			xml+=phones.get(i).getMicrocode()+";";
			micIndex+=phones.get(i).getMicroid()+";";
		}
		xml+="</Url>"+micIndex+"</MicIndex>";
		xml+="<Identify>"+caseid+"</Identify>";
		xml+="</RequestInfo>";
		//解析返回结果
		String Interface_Url=SystemParamService.getValueByCacheId(BizConstants.PARAM_MAP.get("LIVE_URL"));
		if(StringUtils.isEmpty(Interface_Url)){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"系统参数asr地址未配置");
			return vo;
		}
		String resMsg=HttpUtils.doPost(Interface_Url, xml);
		log.info("初始化接口返回结果："+resMsg);
		if(StringUtils.isEmpty(resMsg)){
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"初始化接口失败");
			return vo;
		}
		try{
			XStream xstream=new XStream(new DomDriver());
			xstream.processAnnotations(ResponseInfo.class);
			Object objinfo=xstream.fromXML(resMsg);
			ResponseInfo info=(ResponseInfo)objinfo;
			if("Success".equals(info.getResCode())){
				ResultVo vo=new ResultVo(ReturnCode.SuccessCode,"初始化成功");
				return vo;
			}
			else if(BizConstants.HAS_INIT.equals(info.getErrorNo())){
				ResultVo vo=new ResultVo(ReturnCode.REUPLOAD,"已进行初始化");
				return vo;
			}
			else{
				ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"初始化接口失败");
				return vo;
			}
		}catch(Exception e){
			e.printStackTrace();
			ResultVo vo=new ResultVo(ReturnCode.ErrorCode,"初始化接口失败");
			return vo;
		}
	}
	/***
	 * 根据案件id获取案件信息
	 * @param caseid
	 * @return
	 */
	public static DrVCase getViewById(String caseid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrVCaseMapper mapper=ss.getMapper(DrVCaseMapper.class);
			DrVCaseExample example =new DrVCaseExample();
			DrVCaseExample.Criteria c=example.createCriteria();
			c.andCaseidEqualTo(caseid);
			return mapper.selectByExample(example).get(0);
		}finally{
			ss.close();
		}
	}
	/**
	 * 获取案件列表
	 * @param page
	 * @param rows
	 * @param sort
	 * @param order
	 * @param vo
	 * @return
	 */
	public static PageInfo<DrVCase> getList(int page, int rows, String sort,
			String order, CaseSearchVo vo) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrVCaseMapper mapper=ss.getMapper(DrVCaseMapper.class);
			PageHelper.startPage(page, rows,PageUtil.joinSortFieldOrder(sort, order));
			return new PageInfo<DrVCase>(mapper.findCases(vo));
			
		}finally{
			ss.close();
		}
	}
	/**
	 * 获取活跃中案件
	 * @return
	 */
	public static List<DrCase> getLivingCase() {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			return caseMapper.getLivingCase();
		}finally{
			ss.close();
		}
	}
	/**
	 * 获取临时表
	 * @param caseid
	 * @return
	 */
	public static DrCaseTemp getTempById(String caseid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrCaseTempMapper mapper=ss.getMapper(DrCaseTempMapper.class);
			return mapper.selectByPrimaryKey(caseid);
		}finally{
			ss.close();
		}
	}
	/**
	 * 插入案件记录
	 * @param caseTemp
	 * @param cases
	 * @param loginUser
	 * @param ip
	 * @param string
	 */
	public static boolean insertCase(DrCase caseTemp,
			SystemOperator loginUser, String ip, String string) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			caseMapper.insert(caseTemp);
			//更新案件室状态为使用中
			DrCourtMapper courtmapper=ss.getMapper(DrCourtMapper.class);
			DrCourt newcourt=new DrCourt();
			newcourt.setCourtid(caseTemp.getCourtid());
			newcourt.setStatus(new BigDecimal(3));
			//删除临时表
			DrCaseTempMapper tempMapper=ss.getMapper(DrCaseTempMapper.class);
			tempMapper.deleteByPrimaryKey(caseTemp.getCaseid());
			courtmapper.updateByPrimaryKeySelective(newcourt);
			//插入日志
			SystemLog log=new SystemLog(Codec.UUID(),loginUser.getOperatorid(),ip,"更新案件状态","插入案件信息",new Date());
			SystemLogMapper logMapper=ss.getMapper(SystemLogMapper.class);
			logMapper.insert(log);
			ss.commit();
		}catch(Exception e){
			e.printStackTrace();
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 查询临时表视图
	 * @param caseid
	 * @return
	 */
	public static DrVCaseTemp getTempViewById(String caseid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrVCaseTempMapper mapper=ss.getMapper(DrVCaseTempMapper.class);
			DrVCaseTempExample example =new DrVCaseTempExample();
			DrVCaseTempExample.Criteria c=example.createCriteria();
			c.andCaseidEqualTo(caseid);
			if(mapper.selectByExample(example)!=null&&mapper.selectByExample(example).size()>0){
				return mapper.selectByExample(example).get(0);
			}
			return null;
		}finally{
			ss.close();
		}
	}
	/**
	 * 统计今日案件室数量
	 * @param status 状态
	 * @param today 日期
	 * @return
	 */
	public static long countTodayCourt(BigDecimal status, String today) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			String field=" where 1=1";
			if(new BigDecimal(1).equals(status)){
				field+=" and (status="+status+" or status=4)";
			}
			else{
				field+=" and status="+status;
			}
			return caseMapper.countTodayCourt(status,field,today);
		}finally{
			ss.close();
		}
	}
	/**
	 * 更新案件MP3存放位置
	 * @param cases
	 * @return
	 */
	public static boolean updateVideoPathById(DrCase cases) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			caseMapper.updateByPrimaryKeySelective(cases);
		}catch(Exception e){
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 更新案件状态
	 * @param caseStatusDelete 状态
	 * @param caseid 案件id
	 * @return
	 */
	public static boolean updateCaseStatus(BigDecimal caseStatus, String caseid) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSessionWithoutAutoCommit();
		try{
			DrCaseMapper caseMapper=ss.getMapper(DrCaseMapper.class);
			DrCase cases=new DrCase();
			cases.setCaseid(caseid);
			cases.setStatus(caseStatus);
			caseMapper.updateByPrimaryKeySelective(cases);
			ss.commit();
		}catch(Exception e){
			ss.rollback();
			return false;
		}finally{
			ss.close();
		}
		return true;
	}
	/**
	 * 根据案件编号获取案件信息
	 * @param trim
	 * @return
	 */
	public static DrCase getByCaseCode(String caseCode) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrCaseMapper mapper=ss.getMapper(DrCaseMapper.class);
			DrCaseExample example =new DrCaseExample();
			DrCaseExample.Criteria c=example.createCriteria();
			c.andCasecodeEqualTo(caseCode);
			c.andStatusNotEqualTo(BizConstants.CASE_STATUS_DELETE);
			if(mapper.selectByExample(example)!=null&&mapper.selectByExample(example).size()>0){
				return mapper.selectByExample(example).get(0);
			}
			return null;
		}finally{
			ss.close();
		}
	}
	/**
	 * 根据案件编号获取案件信息
	 * @param trim
	 * @return
	 */
	public static DrCaseTemp getByCaseTempCode(String caseCode) {
		// TODO Auto-generated method stub
		SqlSession ss = SessionFactory.INSTANCE.getSqlSession();
		try{
			DrCaseTempMapper mapper=ss.getMapper(DrCaseTempMapper.class);
			DrCaseTempExample example =new DrCaseTempExample();
			DrCaseTempExample.Criteria c=example.createCriteria();
			c.andCasecodeEqualTo(caseCode);
			if(mapper.selectByExample(example)!=null&&mapper.selectByExample(example).size()>0){
				return mapper.selectByExample(example).get(0);
			}
			return null;
		}finally{
			ss.close();
		}
	}
	
	
}
